package com.ccc.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ccc.dto.Result;
import com.ccc.entity.Shop;
import com.ccc.mapper.ShopMapper;
import com.ccc.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ccc.utils.CacheClient;
import com.ccc.utils.RedisConstants;
import com.ccc.utils.RedisData;
import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private  StringRedisTemplate stringRedisTemplate;
    @Resource
    CacheClient cacheClient;
    @Override
    public Result queryById(Long id) {
        //使用工具类互斥锁
        Shop shop = cacheClient.queryWithMutex(RedisConstants.CACHE_SHOP_KEY
                ,id, Shop.class,this::getById);
        //Shop shop = queryWithLogicalExpire(id);
        if(shop == null){
            return Result.fail("商户不存在!");
        };
        return Result.ok(shop);
    }
    public Shop queryWithMutex(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //缓存命中:返回
        if(StringUtils.isNotBlank(shopJson)){
            return JSONUtil.toBean(shopJson, Shop.class);
        }
        //缓存命中:为缓存空对象,直接返回
        if(shopJson != null){
            return null;
        }
        //缓存未命中:为null->为特定商户对象设互斥锁
        if(!tryLock(id)){
            //未拿到锁的继续等待
            try {
                Thread.sleep(50);
                return queryWithMutex(id);
                //递归, 若查询到则返回
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        //若拿到锁的时候能够缓存命中,释放锁
        try {
            shopJson = stringRedisTemplate.opsForValue().get(key);
            //缓存命中:返回
            if(StringUtils.isNotBlank(shopJson)){
                return JSONUtil.toBean(shopJson, Shop.class);
            }
            Shop shop = getById(id);

            //id不存在:创建缓存空对象,返回
            if (shop == null) {
                stringRedisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            //id存在:创建缓存, 返回
            stringRedisTemplate.opsForValue()
                    .set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
            return shop;
        }
        finally {
            //释放锁
            unLock(id);
        }
    }

    //自定义锁:成功->返回1,即ture
    private boolean tryLock(Long id){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(RedisConstants.LOCK_SHOP_KEY+id,"1"
                , RedisConstants.LOCK_SHOP_TTL, TimeUnit.MINUTES);
        return BooleanUtil.isTrue(flag);
    }
    private void unLock(Long id){
        stringRedisTemplate.delete(RedisConstants.LOCK_SHOP_KEY+id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateId(Shop shop) {
        //
        Long id = shop.getId();
        if(id==null){
            return Result.fail("商户不存在!");
        }
        //更新数据库
        updateById(shop);
        //删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
        return Result.ok();
    }
    public void saveShop2Redis(Long id,Long expireMinutes){
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusMinutes(expireMinutes));
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));
    }
    //逻辑过期缓解缓存击穿
    public Shop queryWithLogicalExpire(Long id){
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        //查询缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);

        //缓存未命中:返回
        if(StringUtils.isBlank(shopJson)){
            return null;
        }
        //缓存命中:查询是否过期
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        JSONObject obj = (JSONObject) redisData.getData();
        Shop shop = JSONUtil.toBean(obj, Shop.class);
        //未过期:返回
        if(redisData.getExpireTime().isAfter(LocalDateTime.now())){
            return shop;
        }
        //过期:进行缓存重建
        if(tryLock(id)){
            //开启线程进行缓存重建
            try {
                Thread thread = new Thread(()->{
                    saveShop2Redis(id,30L);
                });
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                unLock(id);
            }
            //跳出语句, 返回旧数据
        }
        //未拿到锁:返回
            return shop;
    }
}
